<?php

class ShopController extends ApplicationController {
	protected $AppName = "shop";
	public $UseApps = array(array("name" => "mysql"),
							 array("name" => "phpmailer"),
							 array("name" => "smarty"),
							 array("name" => "paginator"),
							 array("name" => "lightboxgallery"));
							 
	protected $IncludeFiles = array("shop.item.class.php", "shop.category.class.php", "shop.cart.class.php");
	
	protected $HeadTags = array("<link rel=\"stylesheet\" type=\"text/css\" href=\"{\$env.url}lib/shop/views/shop.css\" />",
								"<script type=\"text/javascript\" src=\"{\$env.url}lib/shop/shop.js\"></script>");
	
	public $RedirectName = "shop";
	private $ShopCart;
	
	function init(){
		$this->ShopCart = $this->loadShopCart();
		
		$URLPosition = SystemRegistry::getInstance()->get("url_position");
		$HTTP = new HTTPRequest();
		
		$URL_Action = $HTTP->get($URLPosition);
		
		$SmartyC = $this->UseApps["smarty"];
		$Smarty = $SmartyC->getSmarty();
		
		// we make sure the redirecton makes sense
		$Smarty->assign("RedirectName", $this->RedirectName);
		
		switch ($URL_Action){
			case "item":
				$ItemID = $HTTP->get($URLPosition+1);
				
				if(!is_numeric($ItemID)){
					return $this->Language->get("invalid_item_id");
				}
				
				$ShopItem = new ShopItem($ItemID, $this);
				$ItemCategory = new ShopCategory($ShopItem->getCategoryID(), $this);
				
				$Smarty->assign("ShopItem", $ShopItem);
				$Smarty->assign("ItemCategory", $ItemCategory);
				$Smarty->assign("AllCategories", $this->getCategories());
				
				$this->ViewFile = "display_item.tpl";
				
				return true;
			break;
			
			case "category":
				$CategoryID = $HTTP->get($URLPosition+1);
				
				if(!is_numeric($CategoryID)){
					return $this->Language->get("invalid_category_id");
				}
				
				/* PAGINATOR*/
				$CategoryPage = ($HTTP->get($URLPosition+2) === false) ? 1 : $HTTP->get($URLPosition+2);
				$Offset = ($CategoryPage-1) * 10;
				$ShopCategory = new ShopCategory($CategoryID, $this, "LIMIT $Offset, 10");
				$Total = $ShopCategory->getCatItemsQuantity();
						
				$PaginatorC = $this->UseApps["paginator"];
				$Paginator = $PaginatorC->generatePaginator($Total, 10, $CategoryPage * 10);
				
				/* Assign to smarty */
				$Smarty->assign("ShopPaginator", $Paginator);
				$Smarty->assign("ShopCategory", $ShopCategory);
				$Smarty->assign("AllCategories", $this->getCategories());
				
				$this->ViewFile = "display_category.tpl";
				
				return true;
			break;
			
			case "cart":
				$this->ViewFile = "display_cart.tpl";
				
				$Smarty->assign("ShopCart", $this->ShopCart);
				
				return true;
			break;
			
			case "cashier":
				if(isset($_POST["cashierOrder"])){
					return $this->order();
				}
				
				$this->ViewFile = "display_cashier.tpl";
				
				$Smarty->assign("ShopCart", $this->ShopCart);
				
				return true;
			break;
			
			// AJAX FUNCTION
			case "add-to-cart":
				$ItemID = $HTTP->get($URLPosition + 1);
				
				if(is_numeric($ItemID)){
					if($this->ShopCart->addCartItem($ItemID) == true){
						return "added";
					}
				}
				
				return "item not avalible any more";
			break;
			
			// AJAX FUNCTION
			case "change-quantity":
				$ItemID = $HTTP->get($URLPosition + 1);
				$NewQuantity = $_POST["newItemQuantity"];
				
				if(is_numeric($ItemID) && is_numeric($NewQuantity)){
					if($this->ShopCart->changeCartItemQuantity($ItemID, $NewQuantity)){
						return "updated";
					}
				}
				
				return "error updating";
			break;
			
			// AJAX FUNCTION
			case "get-cart-total":
				return ($this->ShopCart->getTotalAmount() == false) ? false : (string)$this->ShopCart->getTotalAmount();
			
			break;
			
			// AJAX FUNCTION
			case "get-item-total":
				$ItemID = $HTTP->get($URLPosition + 1);
				
				if(is_numeric($ItemID)){
					if(($item_total = $this->ShopCart->getItemTotalAmount($ItemID)) != false){
						return ($item_total > 0) ? (string)$item_total : (string)0;
					}
				}
				
				return "error";
			break;	
			
			// AJAX FUNCTION
			case "remove-item":
				$ItemID = $_POST["removeItem"];
				
				if(is_numeric($ItemID)){
					if($this->ShopCart->removeCartItem($ItemID)){
						return "removed";
					}
				}
				
				return "error";
			break;
			
			// AJAX FUNCTION
			case "clear-cart":
				if($this->ShopCart->clearCart()){
					return "cleared";
				}
				
				return "error";
			break;
			
			default:
				$MySQL = $this->UseApps["mysql"];
				
				$SelectLatest = $MySQL->query("SELECT id FROM {$MySQL->getPrefix()}shop_items ORDER BY id DESC");
				$Categories = $this->getCategories();
				
				$LatestItems = array();
				
				while ($item = mysql_fetch_assoc($SelectLatest)) {
					$LatestItems[] = new ShopItem($item["id"], $this);	
				}
				
				$Smarty->assign("category_items", $LatestItems);
				$Smarty->assign("AllCategories", $Categories);
				
				$this->ViewFile = "display_default.tpl";
				
				return true;
			break;	
		}
	}
	
	function redirected($params){
		$this->RedirectName = $params[0];
		
		return $this->init();
	}
	
	function getCategories(){
		$MySQL = $this->UseApps["mysql"];
		
		$SelectCategories = $MySQL->query("SELECT id FROM {$MySQL->getPrefix()}shop_categories ORDER BY category_name ASC");
		
		if(mysql_num_rows($SelectCategories) <= 0){
			return false;
		}
		
		$Categories = array();
				
		while ($cat = mysql_fetch_assoc($SelectCategories)) {
			$Categories[] = new ShopCategory($cat["id"], $this);
		}
		
		return $Categories;
	}
	
	function loadShopCart(){
		if(isset($_SESSION["fms_shop_cart"])){
			$Cart = unserialize($_SESSION["fms_shop_cart"]);
			
			if($Cart instanceof ShopCart){
				return $Cart;
			}
			
			return false;
		}
		
		$Cart = new ShopCart($this);
		
		return $Cart;
	}
	
	function order(){
		if(empty($_POST["name_surname"]) || empty($_POST["address"]) || empty($_POST["city_number"]) || empty($_POST["e_mail"]) || empty($_POST["telephone"])){
			return $this->Language->get("enter_required_data");
		}
		
		$MySQL = $this->UseApps["mysql"];
		$PHPMailerC = $this->UseApps["phpmailer"];
		
		$NameSurname = escape($_POST["name_surname"], $MySQL);
		$Address = escape($_POST["address"], $MySQL);
		$CityNumber = escape($_POST["city_number"], $MySQL);
		if(isEmail($_POST["e_mail"])){
			$Email = $_POST["e_mail"];
		}
		else {
			return $this->Language->get("enter_valid_email");
		}
		$Telephone = escape($_POST["telephone"], $MySQL);
		
		$OrderContent = "<table style=\"border: 1px solid #c0c0c0; padding: 2px; text-align: center;\" border=\"1\">";
		$OrderContent .= "<tr><td style=\"border: 1px dashed #d0d0d0;\"><strong>{$this->Language->get("item_name")}</strong></td><td style=\"border: 1px dashed #d0d0d0;\"><strong>{$this->Language->get("price")}</strong></td><td style=\"border: 1px dashed #d0d0d0;\"><strong>{$this->Language->get("quantity")}</strong></td><td style=\"border: 1px dashed #d0d0d0;\"><strong>{$this->Language->get("total_amount")}</strong></td></tr>";
			foreach ($this->ShopCart->getCartItems() as $CartItem){
				$ItemObject = $CartItem["item"];
				$Quantity = $CartItem["quantity"];
				
				$OrderContent .= "<tr><td style=\"border: 1px dashed #d0d0d0;\">{$ItemObject->getName()} ({$ItemObject->getCode()})</td><td style=\"border: 1px dashed #d0d0d0;\">{$ItemObject->getDiscountPrice()}&euro;</td><td style=\"border: 1px dashed #d0d0d0;\">{$Quantity}</td><td style=\"border: 1px dashed #d0d0d0;\">{$this->ShopCart->getItemTotalAmount($ItemObject->getID())}&euro;</td></tr>"; 
			}
		$OrderContent .= "<tr><td style=\"border: 1px dashed #d0d0d0;\" colspan=\"4\"><strong>{$this->Language->get("total_amount")}: {$this->ShopCart->getTotalAmount()}&euro;</strong></td></tr>";
		$OrderContent .= "</table>";
		
		$CustomerInfo = $this->Language->get("customer_order_information").":\n\n<br /><br />".
		$this->Language->get("name_surname").": ".$NameSurname."\n<br />".$this->Language->get("address").": ".$Address."\n<br />".
		$this->Language->get("city_number").": ".$CityNumber."\n<br />".$this->Language->get("e_mail").": ".$Email."\n<br />".
		$this->Language->get("telephone").": ".$Telephone;
		
		$MailBody = $NameSurname.$this->Language->get("mail_part1")."\n\n<br /><br />".
					$this->Language->get("mail_part2").":\n\n<br /><br />".$OrderContent.
					$this->Language->get("mail_part3")." ".Core::$FMSConfig->getValue("environment", "info_mail").
					"\n\n<br /><br />".$this->Language->get("mail_part4")." ".Core::$FMSConfig->getValue("environment", "page_title")." team\n\n<br /><br />".
					$CustomerInfo;

		
		if($PHPMailerC->sendMail($Email, $MailBody, $this->Language->get("order_subject")) && $PHPMailerC->sendMail(Core::$FMSConfig->getValue("environment", "info_mail"), $MailBody, $this->Language->get("order_subject"))){
			
			$InsertSQL = "INSERT INTO {$MySQL->getPrefix()}shop_orders (order_content) VALUES('{$OrderContent}{$CustomerInfo}')";
			
			$MySQL->query($InsertSQL);
			
			return $this->Language->get("order_subject");
		}
		else {
			return "An error has occured.";
		}
	}
	
	function getShop(){
		return $this;
	}
}

?>